package cn.tedu.ezhaung_project.controller;

import cn.tedu.ezhaung_project.mapper.UserLoginMapper;
import cn.tedu.ezhaung_project.pojo.dto.UserLoginDTO;
import cn.tedu.ezhaung_project.pojo.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserLoginMapper mapper;
    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpServletResponse response,
                     HttpSession session){
        UserLoginVO userVO=mapper.selectByNickname(userLoginDTO.getNickname());
        if(userVO!=null){
            if(userVO.getPassword().equals(userLoginDTO.getPassword())){
                //把登录成功的用户对象保存到会话对象里面
                session.setAttribute("user",userVO);
                //判断是否需要记住用户名和密码
                if(userLoginDTO.getRem()){
                    //创建cookie 把用户名和密码保存进去
                    Cookie c1=new Cookie("nickname",userLoginDTO.getNickname());
                    Cookie c2=new Cookie("password",userLoginDTO.getPassword());
                    //设置保存时间 单位是秒
                    c1.setMaxAge(60*60*24*30);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                return 1;//登录成功
            }
            return 2;//密码错误
        }
        return 3;//用户名不存在
    }
    @RequestMapping("/currentUser")
    public UserLoginVO currentUser(HttpSession session){
        //从当前客户端对应的会话对象里面取出登录的UserVo
        UserLoginVO user=(UserLoginVO) session.getAttribute("user");
        //如果登录过返回user对象 未登录返回null 但是经过JSON字符串转换后到客户端为空字符串
        return user;
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
